<template>
  <div :class="$style.wrapper">
    <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
    <el-tree :current-node-key="currentResourceId"
             :data="treeData"
             :default-expanded-keys="defaultExpandedKeys"
             :expand-on-click-node="false"
             :filter-node-method="filterNode"
             :indent="10"
             :props="defaultProps"
             @node-click="handleNodeClick"
             highlight-current
             node-key="id"
             ref="tree">
    </el-tree>
  </div>
</template>

<script>
import { mapState } from 'vuex';

const toPath = str => {
  let arr = [str.substring(0, 6)];
  let item;
  str = str.substring(6);
  while ((item = str.substring(0, 3))) {
    arr.push(item);
    str = str.substring(3);
  }
  return arr;
};
export default {
  name: 'PsDeviceTree',
  data () {
    return {
      filterText: '',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'showedLabel'
      },
      showTree: false
    };
  },
  methods: {
    handleNodeClick (data) {
      this.$store.commit('resource/setCurrentResourceId', data.id);
      let params = this.$route.params;
      if (params.resourceId !== data.id) {
        params.resourceId = data.id;
        this.$router.push({
          name: this.$route.name,
          params: params
        });
      }
    },
    filterNode (value, data) {
      if (!value) return true;
      return data.label && data.label.indexOf(value) !== -1;
    }
  },
  computed: {
    ...mapState('resource', [
      'devices',
      'domains',
      'currentResourceId'
    ]),
    devicesAndDomainsLoaded () {
      let { devices, domains } = this;
      domains = (domains || []).sort((a, b) => {
        let aValuesNumber = (a.values || {}).number || 0;
        let bValuesNumber = (b.values || {}).number || 0;
        return aValuesNumber - bValuesNumber;
      }).map(domain => {
        domain.showedLabel = domain.label;
        return domain;
      });
      devices = (devices || []).map(device => {
        device.showedLabel = `${device.label} (${device.externalDevId})`;
        return device;
      });
      return {
        devices, domains
      };
    },
    defaultExpandedKeys () {
      return [this.currentResourceId];
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
    devicesAndDomainsLoaded: {
      immediate: true,
      handler (val) {
        if (val.devices && val.domains) {
          let devices = val.devices;
          let domains = val.domains;
          let remapDevices = devices.map((d) => {
            let match = /\/(\d+)\/$/.exec(d.domains);
            let extId = toPath(d.externalDevId);
            let pid = match[1];
            d.extId = extId.join('/');
            d.parentID = pid;
            return d;
          });
          let allResources = remapDevices.concat(domains);
          let allResourcesMap = allResources.reduce((prev, curr) => {
            prev[curr.id] = curr;
            return prev;
          }, {});
          let treeData = allResources.reduce((prev, curr) => {
            let fd = allResourcesMap[curr.parentID];
            if (fd) {
              fd.children = fd.children || [];
              fd.children.push(curr);
              let parentBak = JSON.parse(JSON.stringify(fd));
              delete parentBak.children;
              curr._parent = parentBak;
            } else {
              if (curr.category === 'Domain') {
                prev.push(curr);
              }
            }
            return prev;
          }, []);
          this.treeData = treeData;
        }
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" module>
@import "./../../../style/default/device-tree.scss";
</style>
